//
//  ViewController5.m
//  ceShi12
//
//  Created by RT on 2025/6/25.
//

#import "ViewController5.h"
#import "WMZPageController/WMZPageProtocol.h"
#import "WMZPageController/WMZPageConfig.h"
#import "MarketFinance2Cell3.h"
#import "MarketFinance2Cell1.h"
#import "MarketFinance2Cell2.h"
#import "XLPlainFlowLayout.h"
#import "CustomTableViewCell.h"

#define ZKL_WIDTH       [UIScreen mainScreen].bounds.size.width
#define ZKL_HEIGHT      [UIScreen mainScreen].bounds.size.height

//#define ZKLTOPSTATUS    [[UIApplication sharedApplication] statusBarFrame].size.height
#define ISIPAD          [[UIDevice currentDevice] userInterfaceIdiom] ==UIUserInterfaceIdiomPad

#define RGBColor(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

#define ZKLWidth(w) (round(((ZKL_WIDTH/375.0) * w * 100)) / 100.0)

#define BTOOM3          (IPHONE_X1 ? 20 : 0)

#define nav_Height ( 44.f + Height_StatusBar )
#define w1 ZKLWidth(206)

#define w ZKL_WIDTH - w1

@interface ViewController5 ()<WMZPageProtocol,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CustomTableViewCellDelegate>
/**  */
@property (nonatomic,strong) UICollectionView *collectionViewTop;

@property (nonatomic,strong) XLPlainFlowLayout *FlowLayoutTop;

//@property (nonatomic,strong) XLPlainFlowLayout *FlowLayout;
//
//@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) XLPlainFlowLayout *FlowLayoutLef;

@property (nonatomic,strong) UICollectionView *collectionViewLef;

@property (nonatomic, assign) CGPoint globalCollectionOffset; // 全局同步的偏移量
@property (nonatomic, assign) BOOL isSyncing; // 防止同步循环

/** <#注释#> */
@property(nonatomic, strong) UITableView       *tableView;

@end

@implementation ViewController5
- (NSArray <UIScrollView*>*)getMyScrollViews{
    
    return @[_tableView,_collectionViewLef];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.globalCollectionOffset = CGPointMake(0, 0);

//    [self collectionView];
    
    [self collectionViewTop];
    
    [self collectionViewLef];
        
    [self tableView];

    
}

//TODO: 标题
-(XLPlainFlowLayout *)FlowLayoutTop{
    
    if(!_FlowLayoutTop){
        _FlowLayoutTop = [[XLPlainFlowLayout alloc]init];
        _FlowLayoutTop.naviHeight = 0;
        _FlowLayoutTop.minimumInteritemSpacing = 0;
        _FlowLayoutTop.minimumLineSpacing = 0;
        _FlowLayoutTop.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    
    return _FlowLayoutTop;
}

- (UICollectionView *)collectionViewTop{
    if(!_collectionViewTop){
        
        _collectionViewTop = [[UICollectionView alloc]initWithFrame:CGRectMake(w, 0, w1, ZKLWidth(30)) collectionViewLayout:self.FlowLayoutTop];
        // _collectionView.backgroundColor = UIColor.redColor;
        _collectionViewTop.delegate = self;
        _collectionViewTop.dataSource = self;
//        _collectionViewTop.scrollsToTop = NO;
        _collectionViewTop.showsVerticalScrollIndicator = NO;
        _collectionViewTop.showsHorizontalScrollIndicator = NO;
        _collectionViewTop.bounces = NO;
        [_collectionViewTop registerClass:[MarketFinance2Cell1 class] forCellWithReuseIdentifier:@"cellTop"];
        [self.view addSubview:_collectionViewTop];
    }
    
    return _collectionViewTop;
}

//TODO: 左边名称
-(XLPlainFlowLayout *)FlowLayoutLef{
    
    if(!_FlowLayoutLef){
        _FlowLayoutLef = [[XLPlainFlowLayout alloc]init];
        _FlowLayoutLef.naviHeight = 0;

        _FlowLayoutLef.minimumInteritemSpacing = 0;
        _FlowLayoutLef.minimumLineSpacing = 0;
        _FlowLayoutLef.scrollDirection = UICollectionViewScrollDirectionVertical;
        _FlowLayoutLef.sectionInset = UIEdgeInsetsZero; // 关键设置

    }
    
    return _FlowLayoutLef;
}

- (UICollectionView *)collectionViewLef{
    if(!_collectionViewLef){
        
        _collectionViewLef = [[UICollectionView alloc]initWithFrame:CGRectMake(0, ZKLWidth(30), w, ZKL_HEIGHT-ZKLWidth(74)) collectionViewLayout:self.FlowLayoutLef];
        // _collectionView.backgroundColor = UIColor.redColor;
        _collectionViewLef.delegate = self;
        _collectionViewLef.dataSource = self;
//        _collectionViewLef.scrollsToTop = NO;
        _collectionViewLef.showsVerticalScrollIndicator = NO;
        _collectionViewLef.showsHorizontalScrollIndicator = NO;
        _collectionViewLef.bounces = NO;
        [_collectionViewLef registerClass:[MarketFinance2Cell2 class] forCellWithReuseIdentifier:@"cellLef"];
        [self.view addSubview:_collectionViewLef];
    }
    
    return _collectionViewLef;
}

////TODO: 右下
//-(XLPlainFlowLayout *)FlowLayout{
//    
//    if(!_FlowLayout){
//        _FlowLayout = [[XLPlainFlowLayout alloc]init];
//        _FlowLayout.naviHeight = 0;
//        _FlowLayout.headerReferenceSize = CGSizeZero;
//        _FlowLayout.footerReferenceSize = CGSizeZero;
//        _FlowLayout.minimumInteritemSpacing = 0;
//        _FlowLayout.minimumLineSpacing = 0;
//        _FlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//        _FlowLayout.sectionInset = UIEdgeInsetsZero; // 关键设置
//    }
//    
//    return _FlowLayout;
//}
//
//- (UICollectionView *)collectionView{
//    if(!_collectionView){
//        
//        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(w, 30, w1, ZKL_HEIGHT-ZKLWidth(74)) collectionViewLayout:self.FlowLayout];
//        // _collectionView.backgroundColor = UIColor.redColor;
//        _collectionView.delegate = self;
//        _collectionView.dataSource = self;
//        _collectionView.scrollsToTop = NO;
//        _collectionView.showsVerticalScrollIndicator = NO;
//        _collectionView.showsHorizontalScrollIndicator = NO;
//        _collectionView.bounces = NO;
//        [_collectionView registerClass:[MarketFinance2Cell3 class] forCellWithReuseIdentifier:@"cell"];
//        [self.view addSubview:_collectionView];
//        
////        _collectionView
//    }
//    
//    return _collectionView;
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(collectionViewLayout == _FlowLayoutTop){
        return CGSizeMake(95, 30);
        
    }else if (collectionViewLayout == _FlowLayoutLef){

        return CGSizeMake(w, 30);
        
    }
//    else if (collectionViewLayout == _FlowLayout){
//
//        return CGSizeMake(95, 30);
//        
//    }
    else
    {
        return CGSizeMake(0, 0);
    }
}


//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
////  if (scrollView == self.collectionView){
////        
////        self.collectionViewLef.contentOffset = CGPointMake(self.collectionViewLef.contentOffset.x, self.collectionView.contentOffset.y);
////      self.collectionViewTop.contentOffset = CGPointMake(self.collectionViewLef.contentOffset.x, self.collectionViewTop.contentOffset.y);
////
////        return;
////        
////    }else if (scrollView == self.collectionViewLef){
////        
////        self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, self.collectionViewLef.contentOffset.y);
////        
////        return;
////    }
//    
//}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    // 返回要显示的区的数量
    if(collectionView==self.collectionViewLef){
        return 1;
        
    }else if(collectionView ==self.collectionViewTop){
        return 1;
    }
//    else if(collectionView ==self.collectionView){
//        return 10;
//    }
    
    else{
        return 1;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 返回指定区中的项的数量
    if(collectionView==self.collectionViewLef){
        return 40;
        
    }else if(collectionView ==self.collectionViewTop){
        return 10;
        
    }
//    else if(collectionView ==self.collectionView){
//        return 40;
//        
//    }
    
    else{
        return 0;
    }
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(collectionView == self.collectionViewTop){
        NSString *CellIdentifier = [NSString stringWithFormat:@"CellTop%ld%ld", (long)[indexPath section], (long)[indexPath row]];
        
        [self.collectionViewTop registerClass:[MarketFinance2Cell1 class]  forCellWithReuseIdentifier:CellIdentifier];
        
        MarketFinance2Cell1 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        
//        cell.str = [NSString stringWithFormat:@"2024一季报"];
        cell.name = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];


        return cell;
        
    }else if (collectionView == self.collectionViewLef){
        NSString *CellIdentifier = [NSString stringWithFormat:@"CellLef%ld%ld", (long)[indexPath section], (long)[indexPath row]];
        
        [self.collectionViewLef registerClass:[MarketFinance2Cell2 class]  forCellWithReuseIdentifier:CellIdentifier];
        
        MarketFinance2Cell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.name = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];

        
        return cell;
    }
    
//    else if (collectionView == self.collectionView){
//        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell1%ld%ld", (long)[indexPath section], (long)[indexPath row]];
//        
//        [self.collectionView registerClass:[MarketFinance2Cell3 class]  forCellWithReuseIdentifier:CellIdentifier];
//        
//        MarketFinance2Cell3 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
//        
//        cell.name = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];
//        
//        return cell;
//    }
    else{
        
        return nil;
    }
    
    
}
-(UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(w,ZKLWidth(30),w1, ZKL_HEIGHT-ZKLWidth(75)) style:(UITableViewStylePlain)];
        
        _tableView.showsVerticalScrollIndicator = NO;
        
        //没有数据时不显示tableView的分割线
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.tableHeaderView= [[UIView alloc]initWithFrame:CGRectZero];
        
        _tableView.delegate = self;
        
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.orangeColor;
        //_tableView.state = SKTabViewStateTextColor4;
        
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        
        //         self.tableView.scrollEnabled = NO;
        
        [self.view addSubview:_tableView];
        
        [self.tableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"TableCell"];

//        [_tableView registerClass:[HomMyCell class] forCellReuseIdentifier:@"cell1"];
        
    }
    return _tableView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 40;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    HomContentModel *model = _arrayData[indexPath.row];
    
    return 30;
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];
    
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell == nil) {
        
        cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TableCell"];
        
    }else{
        //防复用设置 删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.indexPathCell = indexPath;

    cell.deletage = self;
    cell.name = @"";
    
//    [cell.collectionView addObject:rightCell.rightCollectionView];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableCell" forIndexPath:indexPath];
      
      // 设置全局同步偏移量
//      if (!CGPointEqualToPoint(self.globalCollectionOffset, CGPointZero)) {
          [cell.collectionView setContentOffset:self.globalCollectionOffset animated:NO];
//      }
//    cell.collectionView.delegate = self;
    
//    [cell.collectionView setContentOffset:self.globalCollectionOffset animated:NO];

    return cell;

}
-(void)CustomTableViewCellScrollViewDidScroll:(UIScrollView *)scrollView{
    __weak __typeof(self)weakSelf = self;
    self.globalCollectionOffset = scrollView.contentOffset;
    [self setHdDong];

    self.collectionViewTop.contentOffset = CGPointMake(self.globalCollectionOffset.x, self.collectionViewTop.contentOffset.y);

        // 只处理 UICollectionView 的滚动
//        if (![scrollView isKindOfClass:[UICollectionView class]]) return;
//    
//        // 防止循环同步
//        if (self.isSyncing) return;
//    
//        // 更新全局偏移量
//        self.globalCollectionOffset = scrollView.contentOffset;
//    
//        // 同步所有可见的 collectionView
//        [self syncAllVisibleCollectionViews];
//    
//        // 同步新出现的单元格（可选）
//        [self syncNextPossibleCells];
    
}
//pragma mark - UICollectionViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if(scrollView==_collectionViewTop){
        self.globalCollectionOffset = scrollView.contentOffset;
        
        [self setHdDong];
        return;
    }else if(scrollView == _collectionViewLef){
        self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.collectionViewLef.contentOffset.y);

        return;
    }else if (scrollView == _tableView){
        self.collectionViewLef.contentOffset = CGPointMake(self.collectionViewLef.contentOffset.x, self.tableView.contentOffset.y);

        return;
    }
}
-(void)setHdDong{
    NSArray *visibleCells = self.tableView.visibleCells;
    __weak __typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        for (CustomTableViewCell *cell in visibleCells) {
//            [weakSelf.ticketLock lock];

            dispatch_async(dispatch_get_main_queue(), ^{
                
                [cell.collectionView setContentOffset:weakSelf.globalCollectionOffset animated:NO];
//                [weakSelf.ticketLock unlock];
            });
        }

    });
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    // 只处理 UICollectionView 的滚动
//    if (![scrollView isKindOfClass:[UICollectionView class]]) return;
//    
//    // 防止循环同步
//    if (self.isSyncing) return;
//    
//    // 更新全局偏移量
//    self.globalCollectionOffset = scrollView.contentOffset;
//    
//    // 同步所有可见的 collectionView
//    [self syncAllVisibleCollectionViews];
//    
//    // 同步新出现的单元格（可选）
//    [self syncNextPossibleCells];
//}
//
//- (void)CustomTableViewCellScrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    if ([scrollView isKindOfClass:[UICollectionView class]]) {
//        self.isSyncing = YES;
//    }
//}
//
//- (void)CustomTableViewCellScrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    if ([scrollView isKindOfClass:[UICollectionView class]]) {
//        // 最终同步所有单元格
//        [self syncAllPossibleCollectionViews];
//        self.isSyncing = NO;
//    }
//}
//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    if ([scrollView isKindOfClass:[UICollectionView class]]) {
//        self.isSyncing = YES;
//    }
//}
//
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    if ([scrollView isKindOfClass:[UICollectionView class]]) {
//        // 最终同步所有单元格
//        [self syncAllPossibleCollectionViews];
//        self.isSyncing = NO;
//    }
//}

#pragma mark - 同步方法

// 同步所有可见的 collectionView
- (void)syncAllVisibleCollectionViews {
    for (CustomTableViewCell *cell in self.tableView.visibleCells) {
        if (!CGPointEqualToPoint(cell.collectionView.contentOffset, self.globalCollectionOffset)) {
            [cell.collectionView setContentOffset:self.globalCollectionOffset animated:NO];
        }
    }
}

// 同步即将出现的单元格（预同步）
- (void)syncNextPossibleCells {
    // 获取当前可见单元格
    NSArray *visibleIndexPaths = [self.tableView indexPathsForVisibleRows];
    if (visibleIndexPaths.count == 0) return;
    
    // 获取最上方和最下方的单元格索引
    NSIndexPath *topIndexPath = visibleIndexPaths.firstObject;
    NSIndexPath *bottomIndexPath = visibleIndexPaths.lastObject;
    
    // 预加载上方单元格
    if (topIndexPath.row > 0) {
        NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:topIndexPath.row - 1 inSection:topIndexPath.section];
        [self syncCellAt:previousIndexPath];
    }
    
    // 预加载下方单元格
    if (bottomIndexPath.row < [self tableView:self.tableView numberOfRowsInSection:0] - 1) {
        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:bottomIndexPath.row + 1 inSection:bottomIndexPath.section];
        [self syncCellAt:nextIndexPath];
    }
}

// 同步指定位置的单元格
- (void)syncCellAt:(NSIndexPath *)indexPath {
    // 检查是否已经在屏幕上
    for (UITableViewCell *cell in self.tableView.visibleCells) {
        if ([self.tableView indexPathForCell:cell].row == indexPath.row) {
            return; // 已经在屏幕上，由其他方法处理
        }
    }
    
    // 获取单元格（强制创建）
    CustomTableViewCell *cell = (CustomTableViewCell *)[self.tableView.dataSource tableView:self.tableView cellForRowAtIndexPath:indexPath];
    
    // 设置同步位置
    [cell.collectionView setContentOffset:self.globalCollectionOffset animated:NO];
    
    // 重要：避免内存泄漏
    cell.collectionView.delegate = self;
}

// 同步所有可能单元格（强力同步）
- (void)syncAllPossibleCollectionViews {
    // 同步当前可见单元格
    [self syncAllVisibleCollectionViews];
    
    // 同步上方单元格
    NSArray *visibleIndexPaths = [self.tableView indexPathsForVisibleRows];
    if (visibleIndexPaths.count == 0) return;
    
    NSInteger minRow = [[visibleIndexPaths valueForKeyPath:@"@min.row"] integerValue];
    NSInteger maxRow = [[visibleIndexPaths valueForKeyPath:@"@max.row"] integerValue];
    
    // 同步上方3行
    for (NSInteger i = MAX(0, minRow - 3); i < minRow; i++) {
        [self syncCellAt:[NSIndexPath indexPathForRow:i inSection:0]];
    }
    
    // 同步下方3行
    for (NSInteger i = maxRow + 1; i <= MIN(maxRow + 3, [self tableView:self.tableView numberOfRowsInSection:0] - 1); i++) {
        [self syncCellAt:[NSIndexPath indexPathForRow:i inSection:0]];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
